package com.fedming.bottomnavigationdemo.Call;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;

import com.fedming.bottomnavigationdemo.R;

import java.lang.ref.WeakReference;

import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity {
    public static final int UPDATE = 0x1;
    public static Handler mHandler;
    private EditText serverEditText;
    private EditText UserEditText;
    private EditText toUserEditText;
    private String server_ip;
    private String userId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //getSupportActionBar().hide();
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        hideBottomUIMenu();
        setContentView(R.layout.activity_main);

        serverEditText = (EditText) findViewById(R.id.ServerEditText);
        UserEditText = (EditText)findViewById(R.id.UserIdEditText);
        toUserEditText = (EditText) findViewById(R.id.toUserEditText);
        //String addr = serverEditText.getText().toString();
        server_ip = serverEditText.getText().toString();

        userId = UserEditText.getText().toString();
        //打开websocket
        my_SignalClient.getInstance().startWebsocket(server_ip, userId,this);
        mHandler = new MyHandler(this);
        findViewById(R.id.do_callBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //String addr = "ws://192.168.31.244:4433/websocket/";

                if(!my_SignalClient.getInstance().websocketIsalive()){
                    my_SignalClient.getInstance().startWebsocket(server_ip, userId,MainActivity.this);

                }
                my_SignalClient.getInstance().userId = userId;
                String toUserId = toUserEditText.getText().toString();
                my_SignalClient.getInstance().toUserId = toUserId;
                my_SignalClient.getInstance().initiator = true; //标志我方为主动拨打的

                if (!"".equals(userId)) {
                    Intent intent = new Intent(MainActivity.this, VideoCallActivity.class);
                    intent.putExtra("ServerAddr", server_ip);
                    intent.putExtra("userid", userId);
                    startActivity(intent);
                }


            }
        });

        String[] perms = {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, "Need permissions for camera & microphone", 0, perms);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        my_SignalClient.getInstance().closeSocket();//销毁MainActivity的时候才能销毁websocket
    }
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {

            Window _window = getWindow();
            WindowManager.LayoutParams params = _window.getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
            _window.setAttributes(params);
        }
    }

    //如果加上static就相当于是一个独立的内部类了，写成静态类后，由于其类似于单独成为了一个类，便不能直接调用我们MainActivity中的一些控件了，所以必须要有一个MainActivity的引用，参考：https://www.jianshu.com/p/23b8ba367c0e
    public static class MyHandler extends Handler{
        WeakReference<MainActivity> mainActivityWeakReference;
        public MyHandler(MainActivity activity) {
            mainActivityWeakReference = new WeakReference<MainActivity>(activity);

        }
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            MainActivity activity = mainActivityWeakReference.get();
            if(activity != null) {
                if (msg.what==UPDATE) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(mainActivityWeakReference.get());
                    builder.setTitle("提示");
                    builder.setMessage(my_SignalClient.getInstance().toUserId + "请求连接，是否接受？");
                    builder.setCancelable(false);
                    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            /*
                            //my_SignalClient.getInstance().comfirm = true;
                            JSONObject tosend = new JSONObject();
                            tosend.put("type","start");
                            JSONObject inner_message = new JSONObject();
                            inner_message.put("userId",my_SignalClient.getInstance().userId);
                            inner_message.put("toUserId",my_SignalClient.getInstance().toUserId);
                            tosend.put("message",inner_message); //json对象的一个value也是json对象
                            //mSocket.send(tosend.toString());
                            my_SignalClient.getInstance().sendMessage(tosend);

                             */
                            Intent intent = new Intent(mainActivityWeakReference.get(), VideoCallActivity.class);
                            //intent.putExtra("ServerAddr", addr);
                            //intent.putExtra("userid", userId);
                            mainActivityWeakReference.get().startActivity(intent);


                        }
                    });
                    builder.setNegativeButton("No", null);
                    builder.show();

                }
            }


        }

    }


}
